<?php

/**
 * Authentication
 * 
 * Authenticates the user and keeps the authentication
 * running based on PHP's session management.
 * 
 * @author Oliver Schwarz <oliver.schwarz@gmail.com>
 * @package Core
 */
class Auth
{

        /**
         * Authenticate a user
         * 
         * @param string $username Username (sanitized)
         * @param string $password Password (sanitized)
         * @return boolean true or false
         */
        public static function authenticate($username, $password)
        {

                $sql = sprintf("
                        SELECT md5(id) AS id FROM users WHERE email = '%s'
                        AND password = MD5('%s')",
                        $username,
                        $password);
                $res = DB::getInstance()->query($sql);
                if ($res->num_rows == 1):
                        $row = $res->fetch_array(MYSQLI_ASSOC);
                        $res->close();
                        $_SESSION[SESSION_PARAM]['userhash'] = $row['id'];
                        return true;
                endif;
                return false;

                /*
                if ($res):
                while ($row = $res->fetch_assoc()):
                        $result[] = $row;
                endwhile;
                endif;
                $res->close();
                Util::debug($result);*/

        }

        /**
         * Fetch user based on session
         * @return array User data of false
         */
        public static function check()
        {

                if (isset($_SESSION[SESSION_PARAM]['userhash'])):
                        $sql = sprintf("
                                SELECT  id, firstname AS name_first,
                                        CONCAT(firstname, ' ', SUBSTRING(lastname, 1, 1), '.') AS name_short,
                                        CONCAT(firstname, ' ', lastname) AS name_full,
                                        CONCAT(lastname, ', ', firstname) AS name_formal,
                                        email
                                FROM users
                                WHERE MD5(id) = '%s'",
                                $_SESSION[SESSION_PARAM]['userhash']);
                        $res = DB::getInstance()->query($sql);
                        if ($res->num_rows == 1):
                                $row = $res->fetch_array(MYSQLI_ASSOC);
                                $res->close();
                                return $row;
                        endif;
                endif;
                return false;
        }

}

?>